﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using DataObjects;
using GT5RemoteMobile.Services;

namespace GT5RemoteMobile
{
    public partial class NewRaceStep3 : System.Web.UI.Page
    {
        Profile psnId;
        string jsessionId;
        protected List<string> friendIds = new List<string>();
        protected Dictionary<string, List<RemoteRaceDriver>> drivers;
        protected void Page_Load(object sender, EventArgs e)
        {
            if(Request.QueryString["addDrivers"] == null)
                Response.Redirect("Default.aspx");
            if (Session["jsessionid"] == null)
                Response.Redirect("Default.aspx");
            jsessionId = Session["jsessionid"].ToString();
            psnId = (Profile)Session["psnUser"];
            string[] driversToAdd = Request.QueryString["addDrivers"].Split(',');

            bool success = false;
            int retryCount = 5;

            foreach (string driver in driversToAdd)
            {
                while (!success)
                {
                    try
                    {
                        if (retryCount == 0)
                            break;
                        AddDriver(driver);
                        success = true;
                    }
                    catch (Exception)
                    {
                        success = false;
                        retryCount--;
                    }
                }

                if (!success)
                    Response.Redirect("default.aspx");
                success = false;
                retryCount = 5;
            }

            // get friends list
            string[] friends = (string[])Session["friends"];
            this.drivers = new Dictionary<string, List<RemoteRaceDriver>>();

            GetDrivers driverUtil = new GetDrivers();
            driverUtil.jsessionId = jsessionId;

            foreach (string friend in friends)
            {
                if (friend.Trim() == psnId.ID)
                    continue;
                friendIds.Add(friend.Trim());

                List<RemoteRaceDriver> rrDriver = new List<RemoteRaceDriver>();
                success = false;
                retryCount = 5;
                while (!success)
                {
                    try
                    {
                        if (retryCount == 0)
                            break;
                        rrDriver = driverUtil.LookupDrivers(friend.Trim());
                        success = true;
                    }
                    catch (Exception)
                    {
                        success = false;
                        retryCount--;
                    }
                }
                                
                if (rrDriver.Count == 0)
                    rrDriver.Add(new RemoteRaceDriver());
                drivers.Add(friend.Trim(), rrDriver);
            }
        }

        private void AddDriver(string driver)
        {
            // hack to get a proper jsession id from gran-turismo.com
            HttpWebRequest profileRequest = WebRequest.Create(new Uri("https://us.gran-turismo.com/us/api/gt5/remoterace/")) as HttpWebRequest;
            //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
#if(DEBUG)
            //profileRequest.Proxy = new WebProxy("localhost", 8888);
#endif
            profileRequest.Method = "POST";
            StreamWriter writer = new StreamWriter(profileRequest.GetRequestStream());

            writer.Write("job=" + (int)RemoteRaceJobType.ADD_ENTRY + "&online_id=" + psnId.ID.Trim() +
                "&driver_id=" + driver);
            writer.Close();
            profileRequest.CookieContainer = new CookieContainer();
            profileRequest.Headers.Add("Cookie", jsessionId);
            profileRequest.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            profileRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

            //foreach (string c in Request.Cookies)
            //{
            //    Cookie cookie = new Cookie(Request.Cookies[c].Name, Request.Cookies[c].Value, Request.Cookies[c].Path, Request.Cookies[c].Domain);
            //    profileRequest.CookieContainer.Add(cookie);
            //}
            using (HttpWebResponse response = profileRequest.GetResponse() as HttpWebResponse)
            {
                // no response here
            }
        }
    }
}